﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using HMIS.FrameWork.Repository.NHb;
using Microsoft.Practices.Unity.InterceptionExtension;
using System.Data;

namespace HMIS.FrameWork.Transaction
{
    /// <summary>
    /// 事务拦截
    /// </summary>
    public class TransactionInterceptor : ICallHandler
    {
        public IsolationLevel Level { get; private set; }
         
        protected virtual ISession Session
        {
            get { return SessionBuilder.CreateSession(); }
        }

        public TransactionInterceptor(IsolationLevel level,int order)
        {
            this.Level = level;
            this.Order = order;
        }

        #region ICallHandler 成员

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            using (ITransaction ts = Session.BeginTransaction(Level))
            {
                try
                {
                    var result = getNext()(input, getNext);
                    ts.Commit();
                    return result;
                }
                catch (HibernateException)
                {
                    ts.Rollback();
                    throw;
                }
            }
        }

        public int Order { get; set; }

        #endregion
    }
}
